package com.ai.dmc.index.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jms.core.JmsTemplate;

public class SpringUtil {
	
	private static ApplicationContext appContext = null;
	private static Logger logger = LoggerFactory.getLogger(SpringUtil.class);
	
	/**
	 * Spring 环境初始化
	 * 
	 * @param configLocations 配置文件路径
	 * @return
	 */
	public static boolean init(String... configLocations) {
		try {
			setAppContext(loadBeanXml(configLocations));
		} catch (Exception e) {
			logger.error("Spring初始化失败！");
			return false;
		}
		return true;
	}

	/**
	 * 得到Spring中配置的JmsTemplate
	 * @return
	 */
	public static JmsTemplate getJmsTopicTemplate() {
		try {
			return (JmsTemplate)getAppContext().getBean("jmsTopicTemplate");
		} catch (BeansException e) {
			logger.error("获取jmsTopicTemplate失败，详细错误为：" + e.getMessage());
			return null;
		}
	}
	
	/**
	 * 得到Spring中配置的JmsTemplate
	 * @return
	 */
	public static JmsTemplate getJmsQueueTemplate() {
		try {
			return (JmsTemplate)getAppContext().getBean("jmsQueueTemplate");
		} catch (BeansException e) {
			logger.error("获取jmsQueueTemplate失败，详细错误为：" + e.getMessage());
			return null;
		}
	}
	
	public static <T> T getBean(Class<T> requiredType) {
		try {
			return getAppContext().getBean(requiredType);
		} catch (BeansException e) {
			logger.error("获取" + requiredType.getName() + "对应的Bean失败，详细错误为：" + e.getMessage());
			return null;
		}
	}
	
	/**
	 * 加载消息监听器的配置文件，配置文件模板见classpath:irms-jms-context.xml
	 * @param path
	 * @return 
	 */
	public static ApplicationContext loadBeanXml(String... configLocations) {
		try {
			return new ClassPathXmlApplicationContext(configLocations);
		} catch (BeansException e) {
			logger.error("加载Spring Bean的配置文件失败，详细错误为：" + e.getMessage());
			return null;
		}
	}
	
	/**
	 * 加载消息监听器的配置文件并指定父ApplicationContext
	 * 
	 * @param parent 
	 * @param configLocations
	 * @return
	 */
	public static ApplicationContext loadBeanXml(ApplicationContext parent, String... configLocations) {
		try {
			return new ClassPathXmlApplicationContext(configLocations, parent);
		} catch (BeansException e) {
			logger.error("加载Spring Bean的配置文件失败，详细错误为：" + e.getMessage());
			return null;
		}
	}

	public static ApplicationContext getAppContext() {
		return appContext;
	}

	public static void setAppContext(ApplicationContext appContext) {
		SpringUtil.appContext = appContext;
	}

}
